package factory;

import game.Board;
import game.Game;
import game.GameDriver;
import game.GameRules;
import game.MoveObtainer;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileGameConfigurator implements GameConfigurator
{

	public FileGameConfigurator()
	{
	}
	
	@Override
	public void createGames(GameDriver driver)
	{
		try
		{
			FileInputStream fstream = new FileInputStream("gameconfig");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String line;

			int i =1;
			while ((line = br.readLine()) != null)
			{
				boolean result = parseLine(line, driver);
				if(result == false)
				{
					System.out.println("Skipping game at line " + i + "!");
				}
				++i;
			}
			in.close();
	    }
		catch (Exception e)
		{
			System.err.println("Error: " + e.getMessage());
		}
	}
	
	private boolean parseLine(String line, GameDriver driver)
	{
		// make sure each line in the configuration file consists of 3 tokens only
		String [] tokens = line.split(",");
		if(tokens.length != 3)
		{
			System.out.println("Illegal game configuration format");
			return false;
		}
		String gameName = tokens[0];
		try
		{
			int numPlayers = Integer.parseInt(tokens[1].trim());
			int numMoves = Integer.parseInt(tokens[2].trim());
			GameFactory factory = null;
			// switch on game name and create a game factory accordingly
			if(gameName.equals("TTT"))
			{
				if(new TTTCreationRules().isValidGame(numPlayers, numMoves) == false)
				{
					return false;
				}
				factory = new TTTGameFactory();
			}
			else
			{
				System.out.println("Illegal game configuration format - I don't know a game named " + gameName);
				return false;
			}
			
			// use the abstract game factory to create and configure the game
			Game game = factory.createGame(gameName, numPlayers, numMoves);
			configureGame(factory, game);
			driver.addGame(game);
			return true;
		}
		catch(NumberFormatException e)
		{
			System.out.println("Illegal game configuration format");
			return false;
		}
	}
	
	private void configureGame(GameFactory factory, Game game)
	{
		Board board = factory.createBoard();
		GameRules rules = factory.createGameRules(game, board);
		MoveObtainer mvObtainer = factory.createMoveObtainer();
		
		game.setItsBoard(board);
		game.setItsGameRules(rules);
		game.setItsMoveObtainer(mvObtainer);
	}
}
